const express = require("express");
const qrcode = require("qrcode");
const jwt = require("jsonwebtoken");

const app = express();

app.use('/static', express.static("scl/static"))
const user = {}
const userId = 1;
app.get("/qrcode", async (req, res) => {
    user[userId] = {
        token: null,
        time: Date.now(), //过期时间，当前记录生成二维码的时间
    }
    const code = await qrcode.toDataURL("http://192.168.1.104:3000/static/empower.html?userId=" + userId);
    res.json({ code, userId })
});
app.post("/login/:userId", (req, res) => {
    const id = req.params.userId;
    const token = jwt.sign({ id }, "gfgbnvgf")
    user[id].token = token;
    user[id].time = Date.now();
    res.json({ token })
})
// 该接口轮询调用检查状态
app.get("/check/:userId", (req, res) => {
    const id = req.params.userId;
    if (Date.now() - user[id].time > 1000 * 60) {
        res.json({ status: 2 }); //超时，已过期
    } else if (user[id].token) {
        // 已授权
        res.json({ status: 1 });
    } else {
        // 未授权
        res.json({ status: 0 });
    }
})
app.listen(3000, () => {
    console.log("server is running at port 3000");
});